import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/http/dao/sms_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/pages/login/local_user_info.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/global.dart';
import 'package:flutter_taotaoshipin/util/other_utils.dart';
import 'package:flutter_taotaoshipin/value/app_profile.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_taotaoshipin/widget/my_app_bar.dart';
import 'package:flutter_taotaoshipin/widget/my_scroll_view.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';

/// 手机号登录
class PhoneLoginPage extends StatefulWidget {
  const PhoneLoginPage({Key? key}) : super(key: key);

  @override
  State<PhoneLoginPage> createState() => _PhoneLoginPageState();
}

class _PhoneLoginPageState extends State<PhoneLoginPage> {
  // 界面类型：绑定手机0，登陆注册1，找回密码2
  int type = 0;

  TextEditingController _phoneController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  FocusNode _phoneNode = FocusNode();
  FocusNode _codeNode = FocusNode();
  bool _isAgreePrivacy = false;
  // 验证码发送按钮是否可用
  bool _smsBtnEnable = true;

  /// 倒计时的计时器。
  Timer? _timer;

  /// 倒计时的秒数，默认60秒。
  final int countdownSecs = 60;

  /// 当前倒计时的秒数。
  int _seconds = 60;

  /// 初始化文本
  String _verifyStr = '获取验证码';

  @override
  void initState() {
    _initData();
    super.initState();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _phoneNode.dispose();
    _codeNode.dispose();
    _timer?.cancel();
    super.dispose();
  }

  _initData() {
    if (Get.arguments != null) {
      Map<String, dynamic> map = Get.arguments;
      type = map['type'] ?? 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        backgroundColor: Colors.transparent,
        hideLine: true,
      ),
      extendBodyBehindAppBar: true,
      backgroundColor: AppColors.app_main,
      body: MyScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 43),
        tapOutsideToDismiss: false,
        keyboardConfig: OtherUtils.getKeyboardActionsConfig(
            context, [_phoneNode, _codeNode]),
        children: [
          SizedBox(height: 132),
          LoadAssetImage(
            'login/logo',
            width: 72,
          ),
          SizedBox(height: 12),
          Text(
            '手机登录',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 7),
          Text(
            '未注册过的手机号将自动创建帐号',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
            ),
          ),
          SizedBox(height: 50),
          TextField(
            controller: _phoneController,
            focusNode: _phoneNode,
            textInputAction: TextInputAction.next,
            keyboardType: TextInputType.phone,
            cursorColor: Colors.white,
            style: TextStyle(color: Colors.white, fontSize: 16),
            decoration: InputDecoration(
              hintText: '请输入手机号',
              hintStyle: TextStyle(color: Colors.white54, fontSize: 16),
              contentPadding: const EdgeInsets.symmetric(vertical: 20),
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.white54)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.white54)),
            ),
          ),
          TextField(
            controller: _codeController,
            focusNode: _codeNode,
            textInputAction: TextInputAction.done,
            keyboardType: TextInputType.number,
            cursorColor: Colors.white,
            style: TextStyle(color: Colors.white, fontSize: 16),
            maxLength: 6,
            decoration: InputDecoration(
              hintText: '请输入验证码',
              hintStyle: TextStyle(color: Colors.white54, fontSize: 16),
              contentPadding: const EdgeInsets.symmetric(vertical: 20),
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.white54)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.white54)),
              suffixIcon: _buildSendCodeBtn(),
            ),
          ),
          SizedBox(height: 22),
          GestureDetector(
            onTap: () {
              setState(() {
                _isAgreePrivacy = !_isAgreePrivacy;
              });
            },
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(
                  _isAgreePrivacy
                      ? Icons.check_circle_rounded
                      : Icons.radio_button_off_rounded,
                  size: 20,
                  color: Colors.white,
                ),
                SizedBox(width: 5),
                Expanded(
                  child: RichText(
                    text: TextSpan(
                      text: '注册登录即表示同意',
                      style: TextStyle(color: Colors.white),
                      children: [
                        TextSpan(
                          text: '《用户协议》',
                          style:
                              TextStyle(decoration: TextDecoration.underline),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              Global.openUserProtocol();
                            },
                        ),
                        TextSpan(text: '和'),
                        TextSpan(
                          text: '《隐私政策》',
                          style:
                              TextStyle(decoration: TextDecoration.underline),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              Global.openPravicyPolicy();
                            },
                        ),
                        TextSpan(text: '并授权闪验获取本机号码'),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 71),
          Container(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: _loginBtnClicked,
              child: Text(
                '登录',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w900),
              ),
              style: ElevatedButton.styleFrom(
                foregroundColor: AppColors.app_main,
                backgroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _loginBtnClicked() {
    if (!_isAgreePrivacy) {
      EasyLoading.showToast('请勾选同意协议');
    } else {
      var text = _phoneController.text.trim();
      if (text.isEmpty) {
        EasyLoading.showToast('请输入验证码');
      } else {
        if (type == 0) {
          _loadBindPhoneData(_phoneController.text, _codeController.text);
        } else if (type == 1) {
          _loadPhoneLoginData(_phoneController.text, _codeController.text);
        }
      }
    }
  }

  /// 发送短信验证码
  Future<bool> _loadSmsSendData(String phone) async {
    var sendSuccess = false;
    try {
      var result = await SmsDao.send(phone: phone, type: type);
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.state == true) {
            // 发送验证码成功
            EasyLoading.showToast('发送验证码成功');
            sendSuccess = true;
          } else {
            EasyLoading.showToast('发送验证码失败');
          }
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
    return sendSuccess;
  }

  /// 用户绑定手机
  Future<void> _loadBindPhoneData(String phone, String code) async {
    try {
      var result = await UserinfoDao.bindPhone(phone: phone, code: code);
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.state == true) {
            if (result.data!.move == 1) {
              // 登陆
              await _loadUserLoginData(
                  result.data!.userName!, result.data!.userPwd!);
            } else {
              // 显示返回信息
              var msg = result.data!.msg.nullSafe;
              if (msg.isEmpty) {
                EasyLoading.showToast('绑定成功');
              }
              // 保存本地
              var appController = Get.find<AppController>();
              var userInfo = LocalUserInfo2(
                user: result.data!.userName,
                password: appController.localUserInfo.password,
                mId: appController.localUserInfo.mId,
                sessionId: appController.localUserInfo.sessionId,
              );
              appController.updateLocaleUserinfo(userInfo);
              // 更新用户中心
              UserinfoDao.updateCenter();
              // 绑定成功
              Get.back();
            }
          } else {
            // 显示返回信息
            var msg = result.data!.msg.nullSafe;
            if (msg.isEmpty) {
              msg = '绑定失败';
            }
            EasyLoading.showToast(msg);
          }
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }

  /// 手机登录
  Future<void> _loadPhoneLoginData(String phone, String code) async {
    try {
      var result = await UserDao.phoneLogin(phone: phone, code: code);
      if (result.code == 0) {
        if (result.data != null) {
          EasyLoading.showToast('登录成功');
          // 保存本地
          var userInfo = LocalUserInfo2(
            mId: result.data!.id.toString(),
            sessionId: result.data!.sessionId,
          );
          var appController = Get.find<AppController>();
          appController.updateLocaleUserinfo(userInfo);
          // 进入主页
          Get.offAllNamed(AppRoutes.rootTab);
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }

  /// 账号密码登录
  Future<void> _loadUserLoginData(String user, String pwd) async {
    // 错误信息
    var errorMsg = '';
    try {
      var result = await UserDao.login(user, pwd);
      if (result.code == 0) {
        // 登录成功
        if (result.data != null) {
          // 请求结果成功，数据不为空
          if (result.data!.id != null && result.data!.sessionId != null) {
            // 保存本地
            var userInfo = LocalUserInfo2(
              user: user,
              password: pwd,
              mId: result.data!.id.toString(),
              sessionId: result.data!.sessionId,
            );
            var appController = Get.find<AppController>();
            appController.updateLocaleUserinfo(userInfo);
            var profile = AppProfile().copyWith(
              chnId: result.data?.dye?.chnId,
              ver: result.data?.dye?.ver,
            );
            // 更新归因
            var chnId = result.data?.dye?.chnId;
            if (chnId != null && chnId != 0) {
              appController.appProfile.chnId = chnId;
            }
            var ver = result.data?.dye?.ver;
            if (ver != null && ver != '') {
              appController.appProfile.ver = ver;
            }
            var agentName = result.data?.dye?.agentName;
            if (agentName != null && agentName != '') {
              appController.appProfile.agentName = agentName;
            }
            appController.updateAppProfile(appController.appProfile);
            // 进入主页
            Get.offAllNamed(AppRoutes.rootTab);
            return;
          } else {
            errorMsg = '登录失败';
          }
        } else {
          errorMsg = '数据为空';
        }
      } else {
        errorMsg = result.message;
      }
    } on HiNetError catch (e) {
      errorMsg = e.message;
    } catch (e) {
      errorMsg = e.toString();
    }
    // 显示错误信息
    EasyLoading.showToast(errorMsg);
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = countdownSecs;
        setState(() {
          _verifyStr = '重新获取';
          _smsBtnEnable = true;
        });
        return;
      }
      _seconds--;
      setState(() {
        _smsBtnEnable = false;
        _verifyStr = '${_seconds}s';
      });
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  _buildSendCodeBtn() {
    return TextButton(
      onPressed: () async {
        if (_smsBtnEnable) {
          var res = await _loadSmsSendData(_phoneController.text);
          if (res) {
            _startTimer();
          } else {
            _cancelTimer();
          }
        }
      },
      style: TextButton.styleFrom(),
      child: Text(
        _verifyStr,
        style: TextStyle(color: Colors.white),
      ),
    );
  }
}
